import router from "@/router";
import Vue from "vue"
import {loginmc, loginmr, loginuser, loginPermissions} from "@/http/api.js"

let g;
router.beforeEach(async (to, from, next) => {
    let token = Vue.prototype.nativeplacestore.get("login");
    if (to.path !== "/login" && !g) {
        let t = JSON.parse(token) || {code: -99999}
        if (t.code == 1000) {
            let lu = await loginUu();
            lu.mr.forEach((v) => {
                if (v.status == 1 && v.islink == 2 && v.menutype == 2) { // 启用        不是外链      菜单
                    let obj = {
                        path: v.path,
                        name: v.path,
                        component: routerCom(v.url),
                    };
                    if(router.matcher.getRoutes().filter(x=>x.name==obj.name).length<=0){ // 解决路由重复添加
                        router.addRoute("home", obj);
                    }
                }
            });
            g = true;
            next({
                path: to.path,
                replace: true,
            });
        } else {
            next({
                path: "/login",
                replace: true,
            });
        }
    } else {
        g = false;
        next();
    }
});

/**
 * 获取前端页面
 * @param view
 * @returns {function(*=): any}
 */
function routerCom(view) {
    return (resolve) => require([`@/views/${view}.vue`], resolve);
}

/**
 * 获取登录信息
 */
function loginUu() {
    return new Promise(async function (resolve, reject) {
        let mc = await loginmc();
        let mr = await loginmr();
        let user = await loginuser();
        let perms = await loginPermissions();
        // console.log('菜单', mc)
        // console.log('路由', mr)
        // console.log('用户', user)
        // console.log('权限', perms)
        Vue.prototype.nativeplacestore.set("userLogin", {mc, mr, user, perms})
        if (Vue.prototype.nativeplacestore.get("userLogin")) {
            resolve({mc, mr, user, perms});
        } else {
            reject({mc, mr, user, perms});
        }
    });
}
